﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System.Collections.Generic;


namespace Akabana.Amf.Amf0
{
    internal sealed class Amf0ReferenceTable : IAmfReferenceTable
    {
        private const int NO_REFERENCE = -1;

        private IList<object> objectRefList = new List<object>();

        private Dictionary<int, int> objectRefIndexMap = new Dictionary<int, int>();

        public void Clear()
        {
            objectRefList.Clear();
            objectRefIndexMap.Clear();
        }

        public int GetObjectIndex(object value)
        {
            int result = NO_REFERENCE;
            /*
            var refernceSize = objectRefList.Count;
            for (int i = 0; i < refernceSize; i++)
            {
                if (value == objectRefList[i])
                {
                    result = i;
                    break;
                }
            }
            */
            if (!objectRefIndexMap.TryGetValue(value.GetHashCode(), out result))
            {
                result = NO_REFERENCE;
            }
            return result;
        }

        public void SetObject(object value)
        {
            objectRefList.Add(value);
            objectRefIndexMap.Add(value.GetHashCode(), objectRefList.Count - 1);
        }

        public object GetObject(int index)
        {
            return objectRefList[index];
        }
    }
}
